//
//  JSTAdWebViewController.m
//  KYKJPackDemo
//
//  Created by 罗新 on 2017/9/7.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTAdWebViewController.h"
#import <WebKit/WebKit.h>
#import "MJRefresh.h"

@interface JSTAdWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic, weak)WKWebView *wkWebView;
@property (nonatomic, weak)UIProgressView *progressView;
@property (nonatomic, strong)WKWebViewConfiguration *wkWebConfig;
@property (nonatomic, strong) NSString *payAdId;
@end

@implementation JSTAdWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self initBackBtn];
    [UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
    [self becomeFirstResponder];
}

- (void)configUI {
    // 进度条
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
    progressView.tintColor = [UIColor greenColor];;
    progressView.trackTintColor = [UIColor whiteColor];
    self.progressView = progressView;
    WKWebView *wkWebView = [[WKWebView alloc] init];
    wkWebView.frame = CGRectMake(0, 0, kDeviceWidth, kDeviceHeight-64);
    wkWebView.backgroundColor = [UIColor whiteColor];
    wkWebView.navigationDelegate = self;
    wkWebView.UIDelegate= self;
    [self.view addSubview:wkWebView];
    [self.view addSubview:progressView];
    [[wkWebView configuration].userContentController addScriptMessageHandler:self name:@"putAds"];
    [wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [wkWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    self.wkWebView = wkWebView;
    wkWebView.navigationDelegate = self;
    wkWebView.UIDelegate = self;
    wkWebView.allowsBackForwardNavigationGestures = YES;
    wkWebView.scrollView.showsVerticalScrollIndicator = NO;
    [wkWebView.scrollView addHeaderWithTarget:self action:@selector(webViewReload)];
    NSString *token = [JSTSystemInfo token];
    NSString *url =  self.urlStr;
    [url containsString:@"?"] ? (url = [url stringByAppendingString:[NSString stringWithFormat:@"&token=%@",token]]): (url = [url stringByAppendingString:[NSString stringWithFormat:@"?token=%@",token]]);
    [wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}

- (void)webViewReload
{
    [self.wkWebView reload];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.subtype == UIEventSubtypeMotionShake) {
        [JSTServer showAlertWithTitle:@"提示" withDetailStr:@"是否清理缓存数据" andConfirmAction:^{
            WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
            [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]
                             completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {
                                 for (WKWebsiteDataRecord *record  in records)
                                 {  
                                     [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes
                                                                               forDataRecords:@[record]
                                                                            completionHandler:^{
                                                                                NSLog(@"Cookies for %@ deleted successfully",record.displayName);
                                                                            }];
                                 }
                             }];
        }];
    }
    return;
}
- (void)initBackBtn
{
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 44., self.navigationController.navigationBar.height)];
    [back setImage:[UIImage imageNamed:@"general_arrow_left_black"]forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backNavItemTapped) forControlEvents:UIControlEventTouchUpInside];
    [back setImageEdgeInsets:UIEdgeInsetsMake(0.0, -44.0, 0.0, 0.0)];
    back.backgroundColor = [UIColor clearColor];
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backButtonItem;
}
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.wkWebView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1 animated:YES];
            [UIView animateWithDuration: 1.0 animations:^{
                self.progressView.alpha = 0.0;
            }completion:^(BOOL finished) {
                self.progressView.hidden = YES;
            }];
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    } else if (object == self.wkWebView &&[keyPath isEqualToString:@"title"]) {
        self.title = self.wkWebView.title;
    }
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [webView.scrollView headerEndRefreshing];
}
//OC在JS调用方法做的处理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"putAds"]){
        self.payAdId = message.body;
    }
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [webView.scrollView headerEndRefreshing];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSArray *paySchemeArr = [[NSUserDefaults standardUserDefaults] objectForKey:@"payScheme"];
    NSString *urlStr = navigationAction.request.URL.absoluteString;
    for (NSString *scheme in paySchemeArr) {
        if ([urlStr hasPrefix:scheme]) {
            if (!self.payAdId) self.payAdId = @"";
            NSDictionary *dic = @{@"adsid":self.payAdId,@"zoneid":self.zoneId};
            [JSTServer requestCPSInfoDataWithDict:dic Success:nil err:nil];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
            decisionHandler(WKNavigationActionPolicyAllow);
        }
    }
     decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)backNavItemTapped{
    if (self.navigationController.viewControllers.count<=1) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else{
        if (self.adViewShowComplict) self.adViewShowComplict();
        [self.navigationController popViewControllerAnimated:YES];
    }
}
// 取消监听
- (void)dealloc {
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.wkWebView removeObserver:self forKeyPath:@"title"];
}

- (NSString *)getToken{
    return IsStrEmpty([JSTSystemInfo token])?[self getAppInfo]:[JSTSystemInfo token];
}
- (NSString *)getAppInfo{
    NSMutableDictionary *vDic = [NSMutableDictionary dictionaryWithDictionary:[JSTHttpClient uaDic]];
    NSData *data = [NSJSONSerialization dataWithJSONObject:vDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *dataStr = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];
    return dataStr;
}


@end
